package com.linewow.xhyy.nihaonew.fragment;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.linewow.xhyy.nihaonew.R;
import com.linewow.xhyy.nihaonew.activity.TopicDetailActivity;
import com.linewow.xhyy.nihaonew.adapter.ImagesInfoAdapterLoad;
import com.linewow.xhyy.nihaonew.base.BaseFragment;
import com.linewow.xhyy.nihaonew.base.BaseInfo;
import com.linewow.xhyy.nihaonew.entity.image.ImagesInfo;
import com.linewow.xhyy.nihaonew.net.api.NiHaoOkgo;
import com.linewow.xhyy.nihaonew.view.ItemOffsetDecoration;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * Created by LXR on 2016/8/31.
 */
public class SearchImageFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {

    @Bind(R.id.search_image_recycler)
    RecyclerView searchImageRecycler;
    @Bind(R.id.search_image_refresh)
    SwipeRefreshLayout searchImageRefresh;
    @Bind(R.id.search_image_mask)
    RelativeLayout searchImageMask;
    private String TAG = "SearchImageFragment";
    private List<ImagesInfo> imagesInfos;
    private int page = 1;
    private ImagesInfoAdapterLoad adapter;

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public View initView() {
        View view = View.inflate(getActivity(), R.layout.fragment_search_image, null);
        ButterKnife.bind(this, view);
        searchImageRefresh.setOnRefreshListener(SearchImageFragment.this);
        searchImageRefresh.setColorSchemeColors(Color.RED, Color.BLACK);
        GridLayoutManager manager = new GridLayoutManager(SearchImageFragment.this.getActivity(), 3);
        manager.setOrientation(GridLayoutManager.VERTICAL);
        searchImageRecycler.setLayoutManager(manager);
        searchImageRecycler.addItemDecoration(new ItemOffsetDecoration(2));
        searchImageRecycler.setItemAnimator(new DefaultItemAnimator());
        searchImageMask.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                hideSoftKeyboard();
                return false;
            }
        });
        searchImageRecycler.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                ImagesInfo imagesInfo= (ImagesInfo) baseQuickAdapter.getData().get(i);
                startDetailActivity(imagesInfo.tid);
            }
        });
        return view;
    }

    @Override
    public void initList() {
        super.initList();
    }

    @Override
    public void initData() {
        super.initData();
        refreshData(page);
    }

    private void refreshData(int i) {
        NiHaoOkgo.simpleImagesInfo(i)
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        showProgressBar();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Func1<BaseInfo<List<ImagesInfo>>, List<ImagesInfo>>() {
                    @Override
                    public List<ImagesInfo> call(BaseInfo<List<ImagesInfo>> listBaseInfo) {
                        List<ImagesInfo> list = new ArrayList<ImagesInfo>();
                        for (int i = 0; i < listBaseInfo.data.size(); i++) {
                            List<ImagesInfo> simpleImagesInfos = listBaseInfo.data.get(i);
                            list.addAll(simpleImagesInfos);
                        }
                        return list;
                    }
                })
                .subscribe(new Action1<List<ImagesInfo>>() {
                    @Override
                    public void call(List<ImagesInfo> simpleImagesInfos) {
                        searchImageRefresh.setRefreshing(false);
                        if (adapter == null) {
                            dismissProgressBar();
                            imagesInfos = simpleImagesInfos;
                            adapter = new ImagesInfoAdapterLoad(imagesInfos);
                            adapter.isFirstOnly(false);
                            adapter.setOnLoadMoreListener(SearchImageFragment.this);
                            searchImageRecycler.setAdapter(adapter);
                        } else {
                            imagesInfos.clear();
                            adapter.addData(simpleImagesInfos);
                        }


                        Log.e(TAG, "总共list的大小" + simpleImagesInfos.size());
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        Log.e(TAG, "错误信息" + throwable.getMessage());
                        showToast(getString(R.string.message_no_internet));
                    }
                });

    }

    private void loadData(int i) {
        NiHaoOkgo.simpleImagesInfo(i)
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Func1<BaseInfo<List<ImagesInfo>>, List<ImagesInfo>>() {
                    @Override
                    public List<ImagesInfo> call(BaseInfo<List<ImagesInfo>> listBaseInfo) {
                        List<ImagesInfo> list = new ArrayList<ImagesInfo>();
                        for (int i = 0; i < listBaseInfo.data.size(); i++) {
                            List<ImagesInfo> simpleImagesInfos = listBaseInfo.data.get(i);
                            list.addAll(simpleImagesInfos);
                        }
                        return list;
                    }
                })
                .subscribe(new Action1<List<ImagesInfo>>() {
                    @Override
                    public void call(List<ImagesInfo> simpleImagesInfos) {
                        if (adapter != null) {
                            adapter.addData(simpleImagesInfos);
                            if (simpleImagesInfos.size() < 18) {
                                adapter.loadComplete();
                            }
                        }
                        Log.e(TAG, "总共list的大小" + imagesInfos.size());
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        Log.e(TAG, "错误信息" + throwable.getMessage());
                    }
                });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onRefresh() {
        page = 1;
        refreshData(page);
    }

    @Override
    public void onLoadMoreRequested() {
        page++;
        loadData(page);
    }

    public void startDetailActivity(String tid){
        Intent intent=new Intent(SearchImageFragment.this.getActivity(), TopicDetailActivity.class);
        intent.putExtra("msg",tid);
        startActivity(intent);
    }

}
